﻿using LtccApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace LtccApi.Controllers
{
    /// <summary>
    /// 登陆
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class LoggedOnController : Controller
    {
        private LtccContext mLtccContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ltccContext"></param>
        public LoggedOnController(LtccContext ltccContext)
        {
            mLtccContext = ltccContext;
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult List(User user)
        {
            List<LoggedOnResult> data = new List<LoggedOnResult>();
            LoggedOnResult loggedOnResult = new LoggedOnResult();
            //异常判断
            if (user == null || !ModelState.IsValid)
            {
                loggedOnResult.Result = "fail";
                data.Add(loggedOnResult);
                return Ok(data);
            }
            //查询账号是否存在
            var userinfo = mLtccContext.Users.Where(m => m.Phone == user.Phone).SingleOrDefault();
            if (userinfo == null)
            {
                loggedOnResult.Result = "fail";
                data.Add(loggedOnResult);
                return Ok(data);
            }
            //查询验证码是否正确
            var checkCode = mLtccContext.CheckCodes.Where(m => m.UserId == userinfo.ID && m.Code == user.CheckCode).SingleOrDefault();
            if (checkCode == null)
            {
                loggedOnResult.Result = "fail";
                data.Add(loggedOnResult);
                return Ok(data);
            }
            //查询验证码是否过期
            DateTime currentTime = DateTime.Now;
            DateTime lastTime = DateTime.ParseExact(checkCode.CurrentTime, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
            long value = (currentTime.Ticks - lastTime.Ticks) / 10000000;  //将时间转换为秒
            if (value > 15 * 60)  //验证码时间为15分钟
            {
                Console.WriteLine("使用过期验证码登陆:{0}", user.Phone);
                loggedOnResult.Result = "fail";
                data.Add(loggedOnResult);
                return Ok(data);
            }
            string hash = Sha1(user.Phone + ":" + user.CheckCode);
            //更新token及时间
            userinfo.LastTime = DateTime.Now.ToString("yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);
            userinfo.Token = hash;
            mLtccContext.Users.Update(userinfo);
            mLtccContext.SaveChanges();
            //返回数据
            loggedOnResult.Result = "success";
            loggedOnResult.Account = user.Phone;
            loggedOnResult.Hash = hash;
            data.Add(loggedOnResult);

            return Ok(data);
        }

        private static string Sha1(string str)
        {
            var buffer = Encoding.UTF8.GetBytes(str);
            var data = SHA1.Create().ComputeHash(buffer);
            var sb = new StringBuilder();
            foreach (var t in data)
            {
                sb.Append(t.ToString("x2"));
            }

            return sb.ToString();
        }
    }
}
